package www.truongnha.com;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import Config.setting;
import TruongNhaLib.DatabaseHandler;
import TruongNhaLib.UserFunctions;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

public class TruongNhaLogin extends Activity {
	//R.id:
	EditText username;
    EditText password;
    Button btnLogin;
    TextView loginErrorMsg;
    boolean error = false;
    TextView registerScreen;
    private static String host = setting.getHost();
    private static String url = host + "api/login/";
    // JSON Response node names
    //Key for user node:
    private static String KEY_SUCCESS = "success";
    private static String KEY_FIRST_NAME = "firstName";
    private static String KEY_LAST_NAME = "lastName";
    private static String KEY_TYPE = "type";// 0- student, 3- teacher
    private static String KEY_CLASS = "class";	
    private static String KEY_SCHOOL = "school";
    private static String KEY_BIRTH = "birth";	
    //Key for teacher node JSON:
    private static String KEY_TEACHER = "teachingClass";	
    private static final String KEY_CLASS_ID = "classId";
    private static final String KEY_CLASS_NAME = "className";
    private static final String KEY_CLASS_SUBJECT = "subject";
    private static final String KEY_CLASS_SIZE = "size";
    private static final String KEY_CLASS_MAINTEACHER = "homeTeacher";
    private static final String KEY_CLASS_SUBJECT_ID = "subjectId";
    //Key for student node JSON:
    //Json array of classes for teacher only:
    JSONArray classes = null;
    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        //alert no network before exit
        if (!isNetworkAvailable()) {
        	Intent i = new Intent(this, NoNetwork.class);
        	startActivityForResult(i, 1);
		}        
        //findViewById from layout:
        username = (EditText)findViewById(R.id.username);
        password = (EditText)findViewById(R.id.password);

        btnLogin = (Button) findViewById(R.id.btnLogin);
        registerScreen = (TextView) findViewById(R.id.link_to_register);
        loginErrorMsg = (TextView) findViewById(R.id.loginErrorMsg);       
        
        final DatabaseHandler db = new DatabaseHandler(getApplicationContext());
        final UserFunctions userFunction = new UserFunctions();
        //Check remember table for previous user
        final Boolean logged = userFunction.isRemember(getApplicationContext());
        //LoginAsyncTask
        class loginTask extends AsyncTask<String, Void, Void >{
        	//JSONObject json;
     	   	ProgressDialog dialog;
     	   	@Override
			protected void onPreExecute() {
				// TODO Auto-generated method 
				super.onPreExecute();
				Log.d("Task", "onPreExecute");
				dialog = new ProgressDialog(TruongNhaLogin.this);
				dialog.setMessage("Connecting...");
				dialog.show();
				Log.d("Task", "onPreExecute");
			}
     	   	@Override
			protected Void doInBackground(String... params) {
				// TODO Auto-generated method stub
     	   		Log.d("Task", "doInBackground");	
     	   		
     	   		//UserFunctions userFunction = new UserFunctions();
     	   		//JSONParser jsonP = new JSONParser();
				//json = jsonP.getJSONFromUrl(params[0]);
     	   		JSONObject json;
	     	   	if(logged){
	     	   		json = userFunction.loginUser(getApplicationContext() );
	     	   	} else{
	     	   		json = userFunction.loginUser(getApplicationContext(), username.getText().toString(), password.getText().toString() );	     	   			     	   		
	     	   		//json = userFunction.loginUser("annd_2012", "annd_2012" );
	     	   	}
     	   		//JSONObject json = userFunction.loginUser("minhnq","minhnq");
				publishProgress();
				// check for login response
                try {
    				Log.d("LOG", "Post 06");
                    if (json.getString(KEY_SUCCESS) != null) {
                    	Log.d("LOG", "Post 07");
                        String res = json.getString(KEY_SUCCESS);
                        if(Integer.parseInt(res) == 1){
                        	Log.d("LOG", "Post 08");
                            // user successfully logged in
                            // Store user details in SQLite Database
                            //DatabaseHandler db = new DatabaseHandler(getApplicationContext());
                            JSONObject json_user = json.getJSONObject("user");
                            Log.d("LOG", "Post 8.5: "+ json_user.toString() );
                            // Clear all previous data in login table in database       
                        	userFunction.delData(getApplicationContext());
                        	Log.d("LOG", "Post 8.7" );         
                            //Store username & password
                        	if(!userFunction.isRemember(getApplicationContext()))
                        		userFunction.addRemember(getApplicationContext(), username.getText().toString(), password.getText().toString(), json_user.getString(KEY_TYPE) );
                            //Add user to database:
                            Log.d("LOG", "Start add user");
                            if(json_user.getInt(KEY_TYPE) == 1) {
                            	db.addUser(json_user.getString(KEY_LAST_NAME), json_user.getString(KEY_FIRST_NAME),json_user.getString(KEY_TYPE), json_user.getString(KEY_CLASS), json_user.getString(KEY_SCHOOL), json_user.getString(KEY_BIRTH), json_user.getString("studentId"));//, "18228"                        								
							} else{
                            	db.addUser(json_user.getString(KEY_LAST_NAME), json_user.getString(KEY_FIRST_NAME),json_user.getString(KEY_TYPE), json_user.getString(KEY_CLASS), json_user.getString(KEY_SCHOOL), json_user.getString(KEY_BIRTH), json_user.getString("teacherId"));//, "18228"                        																
							}
                            Log.d("LOG", "Done add user");
                            if(json_user.getString(KEY_TYPE).toString().equals("3")){
                            	//teacher user with type == 3
                            	// Getting Array of classes
                            	Log.d("LOG", "I'm here 2");
                                classes = json.getJSONArray(KEY_TEACHER);
                                //Looping through All Classes
                                for(int i = 0; i < classes.length(); i++){
                                    JSONObject temp = classes.getJSONObject(i);
                                    if(temp.getString(KEY_CLASS_SUBJECT).equals("-1"))
                                    	db.addClass(temp.getString(KEY_CLASS_ID),temp.getString(KEY_CLASS_NAME), temp.getString(KEY_CLASS_SUBJECT), temp.getString(KEY_CLASS_SIZE), temp.getString(KEY_CLASS_MAINTEACHER), -1);
                                    else
                                    	db.addClass(temp.getString(KEY_CLASS_ID),temp.getString(KEY_CLASS_NAME), temp.getString(KEY_CLASS_SUBJECT), temp.getString(KEY_CLASS_SIZE), temp.getString(KEY_CLASS_MAINTEACHER), temp.getInt(KEY_CLASS_SUBJECT_ID));                     
                                	Log.d("Add class"+ i, temp.getString(KEY_CLASS_NAME)+"|"+ temp.getString(KEY_CLASS_SUBJECT)+"|"+ temp.getString(KEY_CLASS_SIZE)+"|"+ temp.getString(KEY_CLASS_MAINTEACHER));
                                }//End for.
 //                               JSONObject jsonTest = JSONParser.getStudentList("http://10.0.2.2:8080/api/getStudentList/", 1 );
                            } else{
                            	//student user with type ==1 	
                            }//end if.
        
                            /* If user.getString(KEY_TYPE)=1, switch to student screen work
                             * else If user.getString(KEY_TYPE)=3, switch to teacher screen work
                             */
                            if(json_user.getString(KEY_TYPE).equals("1")){
                            	//switch to student screen work
                            	Log.d("LOG", "Post 09: student");
	                            // Switching to LoggedIn -- Work screen
	            				Intent i = new Intent(getApplicationContext(), LoggedIn.class);
	            				startActivity(i);
	                            // Close Login Screen
	                            finish();
                            } else{
                            	//switch to teacher screen work
                            	Log.d("LOG", "Post 09: teacher");
                            	Intent i = new Intent(getApplicationContext(), LoggedIn.class);
	            				startActivity(i);
	                            // Close Login Screen
	                            finish();
                            }//End if
                        }else{
                        	Log.d("LOG", "Post 10");
                            // Error in login
                        	error = true;                            
                        }//end if.
                    }
                } catch (JSONException e) {
                	Log.d("LOG", "Post 12");
                    e.printStackTrace();
                }
				Log.d("Task", "doInBackground");
				return null;
			}
			@Override
			protected void onPostExecute(Void result) {
				// TODO Auto-generated method stub
				super.onPostExecute(result);
				Log.d("Task", "onPostExecute");
				if(dialog.isShowing())
				   {
					   dialog.dismiss();
				   }
				if( error){
					loginErrorMsg.setText(R.string.loginErrorMsg);
					userFunction.logoutUser(getApplicationContext());
				}
				Log.d("Task", "onPostExecute");
			}
			@Override
			protected void onProgressUpdate(Void... values) {
				// TODO Auto-generated method stub
				Log.d("Task", "onProgressUpdate");
				super.onProgressUpdate(values);
				dialog.setMessage("Loading...");
				Log.d("Task", "onProgressUpdate");
			}
        }//end LoginAsyncTask

        //Check remember table for previous user
        if(logged){
        	//login to system immediately
        	//rememberCheckBox.setChecked(true);
        	if(isNetworkAvailable()){
        		//If user session is saved->session will load-> work screen. if NOT-> execute login task
        		if(userFunction.isSavedSession(getApplicationContext())){
    				Intent i = new Intent(getApplicationContext(), LoggedIn.class);
    				startActivity(i);
                    finish();// Close Login Screen
        		}else{
        			new loginTask().execute(url);	        			
        		}
        			
        	}
        }  
        //Listening to login button click:
        btnLogin.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(isNetworkAvailable())
					new loginTask().execute(url);
			}
		});// End listening        
        
        // Listening to register new account link
        registerScreen.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				// Switching to Register screen
				/*Intent i = new Intent(getApplicationContext(), TruongNhaRegister.class);
				startActivity(i);
				*/
				String url = host + "register/";
				Intent i = new Intent(Intent.ACTION_VIEW);
				i.setData(Uri.parse(url));
				startActivity(i);
			}
		});// End listenning
    }
    @Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		Log.d("exit", "exit");
		finish();
    }
	public boolean isNetworkAvailable() {
		   Log.d("Checking", "network");
    	   Context context = getApplicationContext();
    	   ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    	   if (connectivity == null) {
    	   } else {
    	      NetworkInfo[] info = connectivity.getAllNetworkInfo();
    	      if (info != null) {
    	         for (int i = 0; i < info.length; i++) {
    	            if (info[i].getState() == NetworkInfo.State.CONNECTED) {
    	            	Log.d("checking", "ok");
    	            	return true;
    	            }
    	         }
    	      }
    	   }
    	   Log.d("Checking", "No");
    	   return false;
    }//end isNetworkAvailable

}


